<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="showTrademarkDialog">添 加</el-button>
      </div>
    </template>
    <!-- data属性表示表格的数据源 border是让表格有竖线 -->
    <!-- label就是当前列显示的名称 -->
    <!-- prop是当前列要显示的数据 所对应的属性 -->
    <!-- 数据表格项 -->
    <el-table v-loading="loading" :data="trademarkList" border style="width: 100%;margin-bottom:20px;">
      <el-table-column type="index" align="center" label="序号" width="80" />
      <el-table-column prop="tmName" align="center" label="品牌名称" width="180" />
      <el-table-column align="center" label="品牌Logo">
        <template v-slot="{row}">
          <img :src="row.logoUrl" alt="" style="width:100px;">
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{row}">
          <el-button title="编辑品牌" :icon="Edit" type="warning" size="small" @click="editTrademark(row)"/>
          <el-button title="删除品牌" :icon="Delete" type="danger" size="small" @click="delTrademark(row)"/>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3,5,7,10,15]" :small="small" :disabled="disabled" :background="background" layout=" prev, pager, next, jumper,->,sizes,total " :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <!-- 添加品牌时的弹出框结构 -->
    <el-dialog v-model="dialogFormVisible" :title="`${trademark.id?'更新':'添加'}品牌`">
      <el-form ref="trademarkForm" :model="trademark" :rules="rules">
        <el-form-item prop="tmName" label="品牌名称" :label-width="formLabelWidth">
          <el-input v-model="trademark.tmName" autocomplete="off" style="width:70%" />
        </el-form-item>
        <el-form-item prop="logoUrl" label="品牌LOGO" :label-width="formLabelWidth">
          <el-upload class="avatar-uploader" :action="`${BASE_URL}/admin/product/upload`" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar" /> -->
            <img v-if="trademark.logoUrl" :src="trademark.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件,且不超过2M
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary"  @click="submitForm(trademarkForm)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>

</template>

<script lang="ts">
export default {
  name: 'Trademark'
};
</script>

<script setup lang="ts">
import type { UploadProps,FormInstance, FormRules } from 'element-plus';
import { ElMessage,ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { ref, onMounted, reactive } from 'vue';
import { reqDeleteTrademarkInfo, reqGetTrademarkInfoData, reqSaveTrademarkInfo, reqUpdateTrademarkInfo } from '@/api/product/trademark';
import type { TrademarkListModel, TrademarkModel } from '@/api/product/model/trademarkModel';
const currentPage = ref(1);
const pageSize = ref(3);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const total = ref<number>(0);

const loading = ref(true);

// 弹出对话框时用到的相关数据
const dialogFormVisible = ref(false);
const formLabelWidth = '90px';

// 图片上传相关的数据
const imageUrl = ref('');
// console.log('ii',import.meta.env.VITE_API_URL)
const BASE_URL = import.meta.env.VITE_API_URL;

// 定义一个初始化Trademark的函数 用于初始化数据
const initTrademark = () => ({logoUrl:'',tmName:''})
// const form = reactive<TrademarkModel>({
// const trademark = reactive<TrademarkModel>({
//   logoUrl: '', // 图片链接
//   tmName: '' // 品牌名称
// });
const trademark = reactive<TrademarkModel>(initTrademark());
const trademarkForm = ref<FormInstance>()

// 对添加品牌时的数据项内容 做个校验
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '品牌名称不能为空,请重新输入', trigger: 'blur' },
    { min: 2, max: 6, message: '长度应该在2-6之间,请重新输入', trigger: 'blur' },
  ],
  logoUrl: [
    {
      required: true,
      message: '请上传一张图片...',
      trigger: 'change',
    },
  ],
})

// trademarkList当前是使用ref来定义的响应式 因为后期要重新赋值
// 为了保留响应式功能 此时需要使用ref来定义
const trademarkList = ref<TrademarkListModel>([]);

// 1. 定义一个获取品牌数据的函数
const getTrademarkInfoData = async () => {
  const result = await reqGetTrademarkInfoData(currentPage.value, pageSize.value);
  // console.log('trade',result)
  ElMessage.success('获取品牌数据成功了...')
  trademarkList.value = result.records;
  total.value = result.total;

  // 关闭loading效果
  loading.value = false;
};

// 2. 当页面组件挂载完毕之后获取品牌数据
onMounted(() => {
  getTrademarkInfoData();
});

// 3. 当单击页码时 改变页码
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`)
  currentPage.value = val;

  // 重新发送请求 获取数据渲染页面
  getTrademarkInfoData();
};

// 4. 每页显示的数量
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`)
  pageSize.value = val;
  // 还应该从第1页开始显示
  currentPage.value = 1;
  getTrademarkInfoData();
};

// 5. 图片上传成功之后会触发的函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // console.log('uu',uploadFile.raw)
  console.log('rr', response);
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);

  // 将图片在服务器的地址保存一下
  // form.logoUrl = response.data
  trademark.logoUrl = response.data

  // 上传成功之后， 可以手动清除校验提示
};

// 6. 图片上传之前要校验图片格式及大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  const imgTypes = ['image/jpeg', 'image/gif', 'image/png'];
  // if (rawFile.type !== 'image/jpeg') {
  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error('图片格式不正确,应该是jpg/jpeg/gif/png');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小应该是在2M以内,请重新选择...');
    return false;
  }
  return true;
};

// 7. 单击添加 按钮时 弹出对话框 
const showTrademarkDialog = () => {
  Object.assign(trademark, initTrademark())
  // 删除id 
  delete trademark.id
  dialogFormVisible.value = true
}
// 8. 实现添加品牌数据或更新品牌
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    console.log('vv',valid)
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const btnTrademark = async () => {
  // 因为成功了之后才会继续向下执行await之后的代码 
  // await reqSaveTrademarkInfo(form)
  if (trademark.id) {
    await reqUpdateTrademarkInfo(trademark)
  } else {
    await reqSaveTrademarkInfo(trademark)
    currentPage.value = 1 
  }
  ElMessage({
    type: 'success',
    // message:'添加品牌成功...'
    message:'操作品牌成功...'
  })
  dialogFormVisible.value = false

  // 最好是跳转到第1页 有助于查看最新的内容
  // 
  getTrademarkInfoData()

}

// 9. 删除品牌
const delTrademark = (row:TrademarkModel) => {
  ElMessageBox.confirm(
    // '您真的要删除此条数据吗?',
    `您真的要删除${row.tmName}品牌吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
     await reqDeleteTrademarkInfo(row.id as number)
      ElMessage({
        type: 'success',
        message: '删除当前品牌成功',
      })

      // 重新刷新页面
      // currentPage.value = trademarkList.value.length > 1 ? currentPage.value : currentPage.value - 1
      // 要重新 渲染一下当前的页面剩余的数据
      getTrademarkInfoData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}

// 10. 编辑品牌之数据回显
const editTrademark = (row: TrademarkModel) => {
  // 10.1 将待编辑的数据要显示出来 也就是给trademark赋值
  Object.assign(trademark,row)
  // 10.2 弹出对话框
  dialogFormVisible.value = true
}

// 11. 更新品牌和添加品牌是同一个'确定'按钮 实现代码在上面192行
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>